from twisted.web import xmlrpc, server
from provider import *
from twisted.python import log

class DeviceAPI(xmlrpc.XMLRPC):
    """DeviceAPI is used for Devices to register themselves with the Provider"""
    def __init__(self,provider,allowNone=False):
        """Store the parent service"""
        self.provider = provider
        self.allowNone = allowNone
        

    def xmlrpc_updateDeviceSettings(self, devicetoken, badgeSetting, soundSetting, alertSetting):
        """
        Update device in Provider
        Devicetoken: 32byte hex encoded Devicetoken (NSLog(@"Devicetoken: %@", devToken))
        BadgeSetting: True/False  (Receive Badgecount updates)
        SoundSetting: String. False => No Sound Notification; True=> Default    or a custom soundfile name  (limited to 16 chars)
        AlertSetting: String. False => No Alerts; True => All Alerts; Custom => Only alerts matching type 'custom' (limited to 16 chars)
        """
        try:
            self.provider.updateDevice(devicetoken,badgeSetting,soundSetting,alertSetting)
        except InvalidAlertSetting, e:
            raise xmlrpc.Fault(5,"Invalid Alert Setting: %s" % e)
        except InvalidSoundSetting, e:
            raise xmlrpc.Fault(4,"Invalid Soundfile: %s" % e)
        except InvalidBadgeSetting, e:
            raise xmlrpc.Fault(3,"Invalid Badgecount: %s" % e)
        except InvalidDeviceToken, e:
            raise xmlrpc.Fault(2,"Invalid Devicetoken: %s" % e)
        except Exception, e:
            raise xmlrpc.Fault(1,"General Error: %s" % e)
            
        return self.success()
            
    def xmlrpc_badgeReset(self, deviceToken):
        """
        Reset the Badgecount to zero.
        Devicetoken: 32byte hex encoded Devicetoken (NSLog(@"Devicetoken: %@", devToken))
        """
        device = self.getDeviceFromToken(deviceToken)    
        try:
            device.badgeSetTo(0)
        except Exception, e:
            log.err()
            raise xmlrpc.Fault(1,"Error: %s" % e)
        
        return self.success()
    
    def xmlrpc_badgeIncrement(self,deviceToken):
        """Increment Badge by 1
        Devicetoken: 32byte hex encoded Devicetoken (NSLog(@"Devicetoken: %@", devToken))"""
        device = self.getDeviceFromToken(deviceToken)    
        try:
            device.badgeIncrement()
        except Exception, e:
            log.err()
            raise xmlrpc.Fault(1,"Error: %s" % e)
        
        return self.success()
   

    def xmlrpc_badgeDecrement(self,deviceToken):
        """Decrement Badge by 1
        Devicetoken: 32byte hex encoded Devicetoken (NSLog(@"Devicetoken: %@", devToken))"""
        device = self.getDeviceFromToken(deviceToken)    
        try:
            device.badgeDecrement()
        except Exception, e:
            log.err()
            raise xmlrpc.Fault(1,"Error: %s" % e)
        return self.success()
    
    def xmlrpc_badgeSetTo(self, deviceToken, badgeCount):
        """
        Reset the Badgecount to zero.
        Devicetoken: 32byte hex encoded Devicetoken (NSLog(@"Devicetoken: %@", devToken))
        badgeCount:  unsigned integer
        """
        device = self.getDeviceFromToken(deviceToken)    
        try:
            device.badgeSetTo(badgeCount)
        except Exception, e:
            log.err()
            raise xmlrpc.Fault(1,"Error: %s" % e)

        return self.success()
    
    def getDeviceFromToken(self,deviceToken):
        """Get the device Object by specifying the token"""
        try:
            device = list(self.provider.getDevices(deviceToken=deviceToken))[0]
        except NoSuchDevice, e:
            log.err()
            raise xmlrpc.Fault(6,"Invalid DeviceToken: %s" % e)
        except Exception, e:
            log.err()
            raise xmlrpc.Fault(1,"Error: %s" % e)

        return device

        #return self.provider.devices
    
            
    def success(self):
        """What to return in case of success"""
        return "Okay."


class ProviderAPI(DeviceAPI):
    """The Provider API is used to send Messages to devices"""
    
        
    def xmlrpc_register(self,deviceToken):
        """register makes no sense in the ProviderAPI"""
        raise NotImplementedError
    
    def xmlrpc_sendAlert(self,deviceToken,args):
        """Send an Alert to the Device. ()
        Compare: http://developer.apple.com/iphone/library/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/ApplePushService/ApplePushService.html#//apple_ref/doc/uid/TP40008194-CH100-SW20
        deviceToken             theDeviceToken (32byte hex encoded)
        body (String)           The Message Text
        loc-args                All other non keyword arguments (if there are any) are treated as message arguments (loc-key assumed)
        isLocalizable (Bool)    Default is True. If True the body is treated as loc-key.
        incrementBadge (Bool)   Default is True. If True the Badgecount is incremented
        playSound (Bool)        If True the Sound from self.__soundSetting is played.
        hasActionKey (String)   Default is False meaning only an "okay" button is presented. True Means Default button. Alernativly you may specify a custom locaizable Text.
        
        All other keyword arguments are appended as custom payload.
        """
        print dir(self)
        body = args.pop(0)

        #device.sendAlert(args)
        return("Okay")






